<?php
// +----------------------------------------------------------------------
// | RXThinkCMF敏捷开发框架 [ 赋能开发者，助力企业发展 ]
// +----------------------------------------------------------------------
// | 版权所有 2018~2023 南京RXThinkCMF研发中心
// +----------------------------------------------------------------------
// | Licensed LGPL-3.0 RXThinkCMF并不是自由软件，未经许可禁止去掉相关版权
// +----------------------------------------------------------------------
// | 官方网站: https://www.rxthink.cn
// +----------------------------------------------------------------------
// | Author: @牧羊人 团队荣誉出品
// +----------------------------------------------------------------------
// | 版权和免责声明:
// | 本团队对该软件框架产品拥有知识产权（包括但不限于商标权、专利权、著作权、商业秘密等）
// | 均受到相关法律法规的保护，任何个人、组织和单位不得在未经本团队书面授权的情况下对所授权
// | 软件框架产品本身申请相关的知识产权，禁止用于任何违法、侵害他人合法权益等恶意的行为，禁
// | 止用于任何违反我国法律法规的一切项目研发，任何个人、组织和单位用于项目研发而产生的任何
// | 意外、疏忽、合约毁坏、诽谤、版权或知识产权侵犯及其造成的损失 (包括但不限于直接、间接、
// | 附带或衍生的损失等)，本团队不承担任何法律责任，本软件框架禁止任何单位和个人、组织用于
// | 任何违法、侵害他人合法利益等恶意的行为，如有发现违规、违法的犯罪行为，本团队将无条件配
// | 合公安机关调查取证同时保留一切以法律手段起诉的权利，本软件框架只能用于公司和个人内部的
// | 法律所允许的合法合规的软件产品研发，详细声明内容请阅读《框架免责声明》附件；
// +----------------------------------------------------------------------

namespace app\admin\service;

use app\admin\model\Curriculum;
use app\admin\model\Grade;
use app\admin\model\Clazz;
use app\admin\model\Semester;
use app\admin\model\SiteScene;
use app\admin\model\Subject;
use app\admin\model\User;
use app\admin\model\Workandrest;

/**
 * 配置管理-服务类
 * @author 牧羊人
 * @since 2020/11/20
 * Class ConfigService
 * @package app\admin\service
 */
class CurriculumService extends BaseService
{
    /**
     * 构造函数
     * @author 牧羊人
     * @since 2020/11/20
     * ConfigService constructor.
     */
    public function __construct()
    {
        $this->model = new Curriculum();
    }

    /**
     * 获取数据列表
     * @return array
     * @since 2021/5/26
     * @author 牧羊人
     */
    public function getList()
    {
        // \think\Cache::clear();
        $param = request()->param();
        // 查询条件
        $map = [];
        // 日期区间查询
        $type = $param['type'];
        $cId = $param['cId'];
        $startEndTime = isset($param['start_end']) ? json_decode($param['start_end'],true) : [];
        if ($startEndTime && is_array($startEndTime)) {
            // 时间区间查询
            $map[] = ['course_date', 'between', [$startEndTime[0], $startEndTime[1]]];
        }else{
            //返回结果
            $result = array(
                "msg" => '操作成功',
                "code" => 0,
                "data" => [],
                "labelweek" => []
            );

            return $result;
        }
        $dandate = date('Y-m-d');//当前日期
        if ($type==1) {
            $gid = Clazz::where('id',$cId)->value('grade');
        }else{
            $gid = SiteScene::where('id',$cId)->value('grade');
        }
        if ($gid) {
            $sid = Semester::where('FIND_IN_SET(:gid, grade)',['gid'=>$gid])
            ->where('start','<=',$dandate)
            ->where('end','>=',$dandate)
            ->value('id');
            $wid = Workandrest::where(['grade'=>$gid,'semester'=>$sid])->value('id');
            if (!$wid) {
                return message("请先配置作息时间", false);
            }
        }else{
            return message("请先配置学期", false);
        }
        $workdata = json_decode(Workandrest::where(['id'=>$wid])->value('data'),true);
        $data = [];
        $item = [];
        $t = 0;
        if(isset($workdata['zaozi'])&&$workdata['zaozi']==1){
            $t++;
            $item = $this->startcourseEnd($startEndTime[0],$startEndTime[1],$type,$cId,$t,$sid,$wid);
            $item['jie'] = '第'.$t.'节(早自习)';
            $item['jienum'] = $t;
            $item['time'] = implode('~', $workdata['zaozitime']);
            $data[] = $item;
        }
        if(isset($workdata['shang'])&&$workdata['shang']){
            $shang = $workdata['shang'];
            foreach ($shang as $val) {
                $t++;
                $item = $this->startcourseEnd($startEndTime[0],$startEndTime[1],$type,$cId,$t,$sid,$wid);
                $item['jie'] = '第'.$t.'节';
                $item['jienum'] = $t;
                $item['time'] = implode('~', $val);
                $data[] = $item;
            }
        }
        if(isset($workdata['xia'])&&$workdata['xia']){
            $xia = $workdata['xia'];
            foreach ($xia as $val) {
                $t++;
                $item = $this->startcourseEnd($startEndTime[0],$startEndTime[1],$type,$cId,$t,$sid,$wid);
                $item['jie'] = '第'.$t.'节';
                $item['jienum'] = $t;
                $item['time'] = implode('~', $val);
                $data[] = $item;
            }
        }
        if(isset($workdata['wan'])&&$workdata['wan']){
            $wan = $workdata['wan'];
            foreach ($wan as $val) {
                $t++;
                $item = $this->startcourseEnd($startEndTime[0],$startEndTime[1],$type,$cId,$t,$sid,$wid);
                $item['jie'] = '第'.$t.'节';
                $item['jienum'] = $t;
                $item['time'] = implode('~', $val);
                $data[] = $item;
            }
        }
        if(isset($workdata['wanzi'])&&$workdata['wanzi']==1){
            $t++;
            $item = $this->startcourseEnd($startEndTime[0],$startEndTime[1],$type,$cId,$t,$sid,$wid);
            $item['jie'] = '第'.$t.'节(晚自习)';
            $item['jienum'] = $t;
            $item['time'] = implode('~', $workdata['wanzitime']);
            $data[] = $item;
        }
        $labelweek = $this->startdateEnd($startEndTime[0],$startEndTime[1]);
        //返回结果
        $result = array(
            "msg" => '操作成功',
            "code" => 0,
            "data" => $data,
            "sid" => $sid,
            "wid" => $wid,
            "labelweek" => $labelweek
        );

        return $result; // TODO: Change the autogenerated stub
    }

    //获取一周日期数据
    public function startdateEnd($startDate,$endDate){
        $start = new \DateTime($startDate);
        $end = new \DateTime($endDate);
        // 创建一个DatePeriod对象，表示一个日期范围
        $interval = new \DateInterval('P1D'); // 每天一次
        $dateRange = new \DatePeriod($start, $interval, $end->add(new \DateInterval('P1D')));
        $darr = [];
        // 遍历日期范围并处理每一天
        foreach ($dateRange as $k=>$date) {
            // $arr = [];
            // 在这里处理每一天的逻辑
            $ndate = $date->format('Y-m-d');
            $weekday = date('w', strtotime($ndate));
            $weekdays = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'];
            $weekday_text = $weekdays[$weekday];
            if($date->format('m-d')==date('m-d')){
                $dtxt = '今天';
            }else{
                $dtxt = $date->format('m-d');
            }
            $weekdate = $weekday_text."(".$dtxt.")";
            $darr['zhou'.($k+1)] = $weekdate;
            $darr['date'.($k+1)] = $date->format('Y-m-d');
        }
        return $darr;
    }

    //获取一周课程表数据
    public function startcourseEnd($startDate,$endDate,$type,$cId,$t,$sid,$wid){
        $start = new \DateTime($startDate);
        $end = new \DateTime($endDate);
        // 创建一个DatePeriod对象，表示一个日期范围
        $interval = new \DateInterval('P1D'); // 每天一次
        $dateRange = new \DatePeriod($start, $interval, $end->add(new \DateInterval('P1D')));
        $darr = [];
        $where = [];
        $where['type'] = $type;
        $where['semester_id'] = $sid; //默认学期
        $where['tid'] = $cId;
        $where['work_id'] = $wid;//默认作息时间
        $where['course_section'] = $t;
        // 遍历日期范围并处理每一天
        foreach ($dateRange as $k=>$date) {
            $sname = '';
            $uname = '';
            $ndate = $date->format('Y-m-d');
            $where['course_date'] = $ndate;
            $course_id = Curriculum::where($where)->value('course_id');//课程id
            $teacher_id = Curriculum::where($where)->value('teacher_id');//课程id
            if ($course_id) {
                $sname = Subject::where('id',$course_id)->value('name');
            }
            if ($teacher_id) {
                $uname = user::where('id',$teacher_id)->value('realname');
            }
            $weekdata = [];
            $txdata = [];
            if ($sname) {
                $weekdata = [$sname,$uname];
                $txdata = [$course_id,$teacher_id];
            }
            $darr['id'.($k+1)] = Curriculum::where($where)->value('id');
            $darr['zhou'.($k+1)] = $weekdata;
            $darr['dtx'.($k+1)] = $txdata;
        }
        return $darr;
    }

}